package com.aplikata.evok.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.aplikata.bo.AplikataEmail;
import com.aplikata.evok.constants.EvokConstants;
import com.aplikata.evok.constants.EvokEmailConstants;
import com.aplikata.service.PublicServiceImpl;
import com.aplikata.util.AplikataEmailUtil;
import com.aplikata.util.FacesUtil;
import com.aplikata.util.StringUtil;

/** 
* @ClassName: EvokEmailServiceImpl 
* @Description: TODO
* @author Huyun
* @date Oct 31, 2012 10:37:27 AM 
*  
*/
@Service("EvokEmailService")
public class EvokEmailServiceImpl extends PublicServiceImpl implements EvokEmailService {
	private static Log log = LogFactory.getLog(EvokEmailServiceImpl.class);
	
	private String sqlString = " SELECT pat.email, concat(docuf.surname, ' ', docuf.ime) as doctorname, " 
			+ " concat(patuf.surname, ' ', patuf.ime) as patientname, DATE_FORMAT(s.time_from, '%d/%m/%Y %H:%i') as timefrom, s.id "
			+ " FROM evk_doctor_schedule s, _user doc, _user_reference docuf, evk_domain_patient dp, evk_patient p, _user pat, _user_reference patuf "
			+ " WHERE s.status= "
			+ EvokConstants.DOC_RESERVATION_STATUS_NORMAL
			+ " and s.doctor_id = doc.id and now() < s.time_from and doc.id = docuf.user_id"
			+ " AND s.domain_patient_id = dp.id and dp.patient_id = p.id and p.user_id=pat.id"
			+ " AND pat.id = patuf.user_id and patuf.send_email = true and (pat.email is not null and pat.email != '')" 
			+ " AND time_to_sec(timediff(s.time_from, now())) / 3600 <= ";


	/* 
	* Title: sumbitWarn4Reservation
	* Description: 
	* @see com.aplikata.evok.service.EvokEmailService#sumbitWarn4Reservation() 
	*/
	@SuppressWarnings("unchecked")
	@Override
	public void sumbitWarn6Reservation() {
		String sql1 = sqlString + 6 + " AND s.email_amount < 2 ";

		List<Object[]> resultlist = (List<Object[]>) findBySql(sql1);
		if (resultlist != null && !resultlist.isEmpty()) {
			String idstr = "";
			
			for (Object[] obj : resultlist) {
				String email = (String) obj[0];
				List<String> list = new ArrayList<String>();
				list.add(email);

				String contentString = FacesUtil.getEmailMessage(EvokEmailConstants.RESERVATION_CONTENT, new Object[] {
						obj[1], obj[2], obj[3], "aktivan" });

				AplikataEmail aemail = null;
				try {
					aemail = AplikataEmailUtil.prepareAplikataEmail(FacesUtil.getEmailMessage(
							EvokEmailConstants.RESERVATION_SUBJECT, new Object[] { "aktivan" }), contentString, list);
					aemail.getEmail().send();
					idstr += obj[4] + ",";
				} catch (Exception e) {
					log.error("Send warn 6 hours email failed", e);
					try {
						merge(aemail);
					} catch (Exception e1) {
						log.error("save warn 6 hours email failed", e);
					}
				}
			}
			
			if (!StringUtil.isStrEmpty(idstr)) {
				if (idstr.lastIndexOf(",") >= 0) {
					idstr = idstr.substring(0, idstr.length() - 1);
				}
				String updateSql1 = " UPDATE evk_doctor_schedule set email_amount = 2 WHERE status = " 
						+ EvokConstants.DOC_RESERVATION_STATUS_NORMAL
						+ " AND now() <= time_from "
						+ " AND time_to_sec(timediff(time_from, now())) / 3600 <= 6 AND email_amount < 2";
				updateSql1 += " AND id in (" + idstr + ")";
				this.getPublicDao().updateBySql(updateSql1);
			}
		}
	}

	/* 
	* Title: sumbitWarn24Reservation
	* Description: 
	* @see com.aplikata.evok.service.EvokEmailService#sumbitWarn24Reservation() 
	*/
	@SuppressWarnings("unchecked")
	@Override
	public void sumbitWarn24Reservation() {
		String sql1 = sqlString + 24 + " AND s.email_amount < 1 ";
		List<Object[]> resultlist = (List<Object[]>) findBySql(sql1);
		if (resultlist != null && !resultlist.isEmpty()) {
			String idstr = "";
			
			for (Object[] obj : resultlist) {
				String email = (String) obj[0];
				List<String> list = new ArrayList<String>();
				list.add(email);

				String contentString = FacesUtil.getEmailMessage(EvokEmailConstants.RESERVATION_CONTENT, new Object[] {
						obj[1], obj[2], obj[3], "aktivan" });

				AplikataEmail aemail = null;
				try {
					aemail = AplikataEmailUtil.prepareAplikataEmail(FacesUtil.getEmailMessage(
							EvokEmailConstants.RESERVATION_SUBJECT, new Object[] { "aktivan" }), contentString, list);
					aemail.getEmail().send();
					idstr += obj[4] + ",";
				} catch (Exception e) {
					log.error("Send warn 24 hours email failed", e);
					try {
						merge(aemail);
					} catch (Exception e1) {
						log.error("save warn 24 hours email failed", e);
					}
				}
			}
			
			if (!StringUtil.isStrEmpty(idstr)) {
				if (idstr.lastIndexOf(",") >= 0) {
					idstr = idstr.substring(0, idstr.length() - 1);
				}
				String updateSql1 = " UPDATE evk_doctor_schedule set email_amount = 1 WHERE status = " 
						+ EvokConstants.DOC_RESERVATION_STATUS_NORMAL
						+ " AND now() <= time_from "
						+ " AND time_to_sec(timediff(time_from, now())) / 3600 <= 24 AND email_amount = 0 ";
				updateSql1 += " AND id in (" + idstr + ")";
				this.getPublicDao().updateBySql(updateSql1);
			}
		}
	}

	public static void main(String args[]) throws Exception {

	}
}
